"use client"

import { useState, useEffect } from "react"
import EventCard from "@/components/EventCard"
import Timer from "@/components/Timer"
import Fireworks from "@/components/Fireworks"
import { Button } from "@/components/ui/button"
import { getRandomEvents, findClosestEvent } from "@/utils/gameLogic"
import type { Library, HistoricalEvent } from "@/types"

interface GamePageProps {
  selectedLibraries: Library[]
  onGameFinish: (score: number) => void
  onAbandonGame: () => void
  choiceCount: number
}

export default function GamePage({ selectedLibraries, onGameFinish, onAbandonGame, choiceCount }: GamePageProps) {
  const [round, setRound] = useState(1)
  const [score, setScore] = useState(0)
  const [anchorEvent, setAnchorEvent] = useState<HistoricalEvent | null>(null)
  const [choiceEvents, setChoiceEvents] = useState<HistoricalEvent[]>([])
  const [selectedEvent, setSelectedEvent] = useState<HistoricalEvent | null>(null)
  const [showAnswer, setShowAnswer] = useState(false)
  const [isCorrect, setIsCorrect] = useState(false)
  const [showFireworks, setShowFireworks] = useState(false)

  useEffect(() => {
    startNewRound()
  }, [])

  const startNewRound = () => {
    const events = getRandomEvents(selectedLibraries, choiceCount + 1)
    setAnchorEvent(events[0])
    setChoiceEvents(events.slice(1))
    setSelectedEvent(null)
    setShowAnswer(false)
    setIsCorrect(false)
    setShowFireworks(false)
  }

  const handleEventSelect = (event: HistoricalEvent) => {
    setSelectedEvent(event)
    const closestEvent = findClosestEvent(anchorEvent!, choiceEvents)
    const correct = event === closestEvent
    setIsCorrect(correct)
    setShowAnswer(true)
    setScore((prevScore) => (correct ? prevScore + 10 : prevScore))
    if (correct) {
      setShowFireworks(true)
      setTimeout(() => setShowFireworks(false), 3000)
    }
  }

  const handleNextRound = () => {
    if (round < 10) {
      setRound((prevRound) => prevRound + 1)
      startNewRound()
    } else {
      onGameFinish(score)
    }
  }

  const handleTimeout = () => {
    if (!selectedEvent) {
      setShowAnswer(true)
    }
  }

  return (
    <div className="text-center">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-2xl font-bold text-white">Round {round}/10</h2>
        <p className="text-xl text-white">Score: {score}</p>
        <Button onClick={onAbandonGame} className="bg-red-300 hover:bg-red-400 text-white font-bold py-2 px-4 rounded">
          Stop Game
        </Button>
      </div>
      {anchorEvent && (
        <div className="mb-6">
          <EventCard event={anchorEvent} isAnchor showDate />
        </div>
      )}
      <div
        className={`grid ${choiceCount === 2 ? "grid-cols-2" : choiceCount > 3 ? "grid-cols-1 md:grid-cols-2" : "grid-cols-1 md:grid-cols-3"} gap-4 mb-6`}
      >
        {choiceEvents.map((event) => (
          <EventCard
            key={event.id}
            event={event}
            onClick={() => !showAnswer && handleEventSelect(event)}
            isSelected={event === selectedEvent}
            isCorrect={showAnswer && event === findClosestEvent(anchorEvent!, choiceEvents)}
            showDate={showAnswer}
          />
        ))}
      </div>
      {!showAnswer && <Timer duration={15} onTimeout={handleTimeout} />}
      {showAnswer && (
        <div className="mt-4">
          <p className="text-xl font-bold mb-2 text-white">
            {isCorrect ? "Correct! +10 points" : "Incorrect. No points awarded."}
          </p>
          <Button
            onClick={handleNextRound}
            className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded"
          >
            {round < 10 ? "Next Round" : "Finish Game"}
          </Button>
        </div>
      )}
      {showFireworks && <Fireworks />}
    </div>
  )
}

